package com.yjkf.zh.admin.service.impl;

import com.yjkf.zh.admin.dao.SysDeptMapper;
import com.yjkf.zh.admin.model.SysDept;
import com.yjkf.zh.admin.service.SysDeptService;
import com.yjkf.zh.core.page.MybatisPageHelper;
import com.yjkf.zh.core.page.PageRequest;
import com.yjkf.zh.core.page.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

  //@CachePut(value = "record")
    @Override
    public int save(SysDept record) {
        if(record.getId() == null || record.getId() == 0){
           return sysDeptMapper.insertDept(record);
        }
        return sysDeptMapper.updateDept(record);
    }

  //  @CacheEvict(value = "record")
    @Override
    public int delete(SysDept record) {
        return sysDeptMapper.deleteByDept(record.getId());
    }

    @Override
    public int delete(List<SysDept> records) {
        for(SysDept record:records) {
            delete(record);
        }
        return 1;
    }


    @Override
    public SysDept findById(Long id) {
        return null;
    }

   // @Cacheable(value = "deptPage")
    @Override
    public PageResult findPage(PageRequest pageRequest) {
        return MybatisPageHelper.findPage(pageRequest,sysDeptMapper);
    }

   // @Cacheable(value = "deptTee")
    @Override
    public List<SysDept> findTree(Long userId) {
        List<SysDept> sysDepts = new ArrayList<>();
        List<SysDept> depts = sysDeptMapper.findDeptForCreateId(userId);
        for(SysDept sysDept : depts){
            if(sysDept.getParentId() == null || sysDept.getParentId() == 0){
                sysDept.setLevel(0);
                sysDepts.add(sysDept);
            }
        }
        findChildren(sysDepts,depts);
        return sysDepts;
    }

    private void findChildren(List<SysDept> sysDepts,List<SysDept> depts){
        for(SysDept sysDept : sysDepts){
            List<SysDept> children = new ArrayList<>();
            for(SysDept dept : depts){
                if(sysDept.getId() != null && sysDept.getId().equals(dept.getParentId())){
                    dept.setParentName(dept.getDeptName());
                    dept.setLevel(sysDept.getLevel() +1);
                    children.add(dept);
                }
            }
            sysDept.setChildren(children);
            findChildren(children,depts);
        }
    }
}
